import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd';
import { v4 as UUID } from 'uuid';

@Component({
  selector: 'zepride-add-memo-item',
  templateUrl: './add-memo-item.component.html',
  styleUrls: ['./add-memo-item.component.less']
})
export class AddMemoItemComponent implements OnInit {

  formGroup: FormGroup;
  @Input() currentDate = new Date();

  constructor(
    private fb: FormBuilder,
    private modalRef: NzModalRef<AddMemoItemComponent>
  ) {
    this.buildForm();
  }

  ngOnInit(): void { }

  buildForm() {
    this.formGroup = this.fb.group({
      title: ['', [Validators.required]],
      start: [this.currentDate, [Validators.required]],
      end: [this.currentDate, [Validators.required]],
      content: ['', [Validators.required]]
    });
  }

  confirm() {
    this.validateForm();
    if (this.formGroup.valid) {
      const value = this.formGroup.value;
      const item: MemoItem = {
        id: UUID().replace(/-/g, ''),
        title: value.title,
        content: value.content,
        timeStart: value.start,
        timeEnd: value.end
      };
      this.modalRef.destroy(item);
    }
  }

  cancel() {
    this.modalRef.destroy();
  }

  validateForm() {
    for (const control in this.formGroup.controls) {
      if (Object.prototype.hasOwnProperty.call(this.formGroup.controls, control)) {
        const element = this.formGroup.controls[control];
        element.markAsDirty();
        element.updateValueAndValidity();
      }
    }
  }

  getDataFromForm() {
    this.formGroup.value;
  }

}

interface MemoItem {
  type?: 'system' | 'person';
  title: string;
  content: string;
  id: string;
  date?: string;
  timeStart: Date;
  timeEnd: Date;
}
